//
//  NetBaseRequest.m
//  ProjectPublic
//
//  Created by ac-hu on 2018/7/6.
//  Copyright © 2018年 ac hu. All rights reserved.
//

#import "NetBaseRequest.h"
#import <AFNetworking.h>

NSString * const netBasetErrorStr = @"参数为空";
NSString * const netLoadingStr = @"loading...";
#define imageCompress 1

@implementation NetBaseRequest

+(void)get:(NSString *)urlStr dic:(NSDictionary *)dic succeed:(succeedNetBlock)succeedBlock fail:(failNetBlock)failBlock{
    
    if (urlStr.length == 0) {
        failBlock(netBasetErrorStr);
        return;
    }
    
    MBProgressHUD *hud = [self getHud];
    [hud showAnimated:YES];
    hud.progress = 0.5;
    
    [[self getNetManager] GET:urlStr parameters:dic progress:^(NSProgress * _Nonnull downloadProgress) {
        dispatch_async(dispatch_get_main_queue(), ^{
            hud.progress = downloadProgress.fractionCompleted;
        });
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        sleep(10);
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
//        if ([resultDic objectForKey:@"code"] == 错误) {
//            failBlock(@"错误文本");
//        }
        succeedBlock(resultDic);
        dispatch_async(dispatch_get_main_queue(), ^{
            [hud hideAnimated:YES];
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        sleep(10);
        failBlock(error.description);
        dispatch_async(dispatch_get_main_queue(), ^{
            [hud hideAnimated:YES];
        });
    }];
}

+(void)post:(NSString *)urlStr dic:(NSDictionary *)dic succeed:(succeedNetBlock)succeedBlock fail:(failNetBlock)failBlock{
    if (urlStr.length == 0) {
        failBlock(netBasetErrorStr);
        return;
    }
    if (dic == nil) {
        failBlock(netBasetErrorStr);
        return;
    }
    
    
    [[self getNetManager] POST:urlStr parameters:dic progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        //        if ([resultDic objectForKey:@"code"] == 错误) {
        //            failBlock(@"错误文本");
        //        }
        succeedBlock(resultDic);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failBlock(error.description);
    }];
}

+(void)upload:(NSString *)urlStr dic:(NSDictionary *)dic images:(NSArray *)images succeed:(succeedNetBlock)succeedBlock fail:(failNetBlock)failBlock{
    
    [[self getNetManager] POST:urlStr  parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        for (int i = 0; i < images.count; i ++) {
            UIImage *image = images[i];
            NSData *imageData = UIImageJPEGRepresentation(image, imageCompress);
            NSString *fileName = [NSString stringWithFormat:@"%@.jpg", [NSString createName]];
            [formData appendPartWithFileData:imageData name:[NSString stringWithFormat:@"file"] fileName:fileName mimeType:@"image/jpg"];
            
        }
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        //        if ([resultDic objectForKey:@"code"] == 错误) {
        //            failBlock(@"错误文本");
        //        }
        succeedBlock(resultDic);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //抛出错误信息
        failBlock(error.description);
    }];
}

+(AFHTTPSessionManager *)getNetManager{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/javascript",@"text/html",@"text/plain",nil];
//    [manager.requestSerializer setValue:@"" forHTTPHeaderField:@"token"];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    return manager;
}

+(MBProgressHUD *)getHud{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    hud.mode = MBProgressHUDModeAnnularDeterminate;
    hud.label.text = netLoadingStr;
    [[UIApplication sharedApplication].keyWindow addSubview:hud];
    return hud;
}

@end
